/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tracnghiem.controller;

import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import tracnghiem.dom.LoginInfo;
import tracnghiem.model.UrlConstants;
import tracnghiem.service.LoginService;

/**
 *
 * @author tjtyler
 */
public class LoginController extends SimpleFormController {

    private LoginService loginService;
    private LocaleResolver localeResolver;

    public LoginController() {
        super();

        setSessionForm(true);
        setCommandName("login");
        setCommandClass(LoginInfo.class);
        setFormView(UrlConstants.LOGIN_URL);
        setSuccessView(UrlConstants.REDIRECT_PREFIX
                + UrlConstants.HOME_URL);
    }

    public void setLoginService(LoginService loginService) {
        this.loginService = loginService;
    }

    public LocaleResolver getLocaleResolver() {
        return localeResolver;
    }

    /**
     * @param localeResolver
     *            the localeResolver to set
     */
    public void setLocaleResolver(LocaleResolver localeResolver) {
        this.localeResolver = localeResolver;
    }

    @Override
    protected ModelAndView onSubmit(HttpServletRequest request,
            HttpServletResponse response, Object command, BindException errors)
            throws Exception {

        LoginInfo loginInfo = (LoginInfo) command;
        if (!loginService.checkLogin(loginInfo)) {
            errors.rejectValue("username", "login.error");
            return showForm(request, response, errors);
        }
        return super.onSubmit(request,
                response, command, errors);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected ModelAndView showForm(HttpServletRequest request,
            HttpServletResponse response, BindException errors)
            throws Exception {
        Locale locale = getLocaleResolver().resolveLocale(request);
        request.setAttribute("locale", locale);        
        return super.showForm(request, response, errors);
    }
}
